package com.chj.exchange.direct;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 一个队列多个消费者，则会表现出消息在消费者之间的轮询发送。
 */
public class MultiConsumerOneQueue {
    private static class ConsumerWorker implements Runnable {
        final Connection connection;
        final String queueName;
        public ConsumerWorker(Connection connection,String queueName) {
            this.connection = connection;
            this.queueName = queueName;
        }
        public void run() {
            try {
                final Channel channel = connection.createChannel();
                // 在信道中设置交换器
                channel.exchangeDeclare(DirectProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
                // TODO：声明一个队列,rabbitmq，如果队列已存在，不会重复创建
                channel.queueDeclare(queueName, false,false, false,null);
                // TODO：队列绑定到交换器上时，是允许绑定多个路由键的，也就是多重绑定
                String[] routeKeys ={"hankin01","hankin02","hankin03"};
                for(String routeKey : routeKeys){
                    channel.queueBind(queueName, DirectProducer.EXCHANGE_NAME, routeKey);
                }
                System.out.println(" [*] Waiting for messages:");
                // 创建队列消费者
                final DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope,
                                               AMQP.BasicProperties properties,
                                               byte[] body) throws IOException {
                        String message = new String(body,"UTF-8");
                        System.out.println("Received["+envelope.getRoutingKey()+"]"+message+", channel=="+channel.getChannelNumber());
                    }
                };
                // TODO 消息者正是开始在指定队列上消费。这里第二个参数是自动确认参数，如果是true则是自动确认
                channel.basicConsume(queueName,true,consumer);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] argv) throws IOException,
            InterruptedException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        // 3个线程，线程之间共享队列,一个队列多个消费者
        String queueName = "focusAll";
        for(int i=0;i<3;i++){
            /*将队列名作为参数，传递给每个线程*/
            Thread worker =new Thread(new ConsumerWorker(connection,queueName));
            worker.start();
        }
    }

}
